#!/Users/hepeng/.pyenv/shims/python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/4 11:12 上午
# @Author  : hepeng
# @Site    : 
# @File    : MainDBDomain.py

from __future__ import unicode_literals
import os,random,string

bin_file = ['mysqld', 'mysqladmin', 'mysqld_safe']
scripts_file = ['mysql_install_db']

class MainDBDomain(object):
    def __init__(self, base_db_path, version=None, length=4):
        if not os.path.exists(base_db_path):
            raise ValueError("base dir isn't exists. base dir:%s" % base_db_path)
        self._base_db_path = base_db_path
        self._bin_path = os.path.join(base_db_path, 'bin')
        self._scripts_path = os.path.join(base_db_path, 'scripts')
        self._support_files_path = os.path.join(base_db_path, 'support-files')
        if not version:
            self._alias = 'mysql' + version
        else:
            self._alias = 'mysql' + random.sample(string.ascii_lowercase + string.digits, length)

    def __check_common_dir(self, dir, baseline_files):
        isOK = False
        if not os.path.exists(dir):
            raise ValueError("%s isn't exists." % dir)
        sub_dirs = os.listdir(dir)
        count = 0
        for sub_dir in sub_dirs:
            if sub_dir in baseline_files and os.path.isfile(os.path.join(dir, sub_dir)):
                count += 1
        if len(baseline_files) == count:
            isOK = True
        return isOK

    def check_bin_dir(self):
        return self.__check_common_dir(self._bin_path, bin_file)

    def check_scripts_dir(self):
        return self.__check_common_dir(self._scripts_path, scripts_file)

    @property
    def alias(self):
        return self._alias

    @property
    def db_base_dir(self):
        return self._base_db_path

    @property
    def sql_server_path(self):
        return os.path.join(self._support_files_path,'mysql.server')
